package com.netty.junjie.socket.handler;

import com.netty.junjie.socket.entity.ConversionData;
import com.netty.junjie.socket.entity.DataAnalysis;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import io.netty.channel.ChannelHandler.Sharable;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import static com.netty.junjie.common.ByteUtils.encodeHexStr;

/**
 * *
 * NettyServerHandler 业务处理Handler
 *
 * @author JunJie
 * @Date 2020/07/13 07:13
 **/
@Component
@Sharable
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        List list = new ArrayList();
        ConversionData conversionData;
        DataAnalysis dataAnalysis = new DataAnalysis();
        log.debug("<<<<===============数据转换===============>>>>");
        try {
            conversionData = (ConversionData) msg;
        } catch (Exception e) {
            log.error("<<<<===============转换失败===============>>>>");
            throw new IndexOutOfBoundsException();
        }
        String str = encodeHexStr(conversionData.getDataBytes());
        String newStr = "";
        for (int i = 1; i <= conversionData.getGroupNumber(); i++) {
            newStr = str.substring((i - 1) * 24, 24 * i);
            list.add(newStr);
            conversionData.setData(list);
        }
        for (Object dataObject : conversionData.getData()) {
            String data = dataObject.toString();
            //定位器MAC地址
            dataAnalysis.setMac(data.substring(0, 4));
            //坐标X
            dataAnalysis.setX(Float.intBitsToFloat(Integer.valueOf(data.substring(4, 12).trim(), 16)));
            //坐标Y
            dataAnalysis.setY(Float.intBitsToFloat(Integer.valueOf(data.substring(12, 20).trim(), 16)));
            //地图编号
            int mapNumber = Integer.parseInt(data.substring(20, 22));
            dataAnalysis.setMapNumber(mapNumber);
            //预留位
            int reserved = Integer.parseInt(data.substring(22, 24));
            dataAnalysis.setReserved(reserved);
            log.debug("<<<<==定位器MAC地址: " + dataAnalysis.getMac() + " 经度: " + dataAnalysis.getX() + " 纬度: " + dataAnalysis.getY() + " 地图编号: " + dataAnalysis.getMapNumber() + " 电量等级为: " + dataAnalysis.getReserved() + " ==>>>>");
            log.debug("<<<<===============转换结束===============>>>>");
            log.debug("<<<<===============业务处理===============>>>>");
            //TODO 业务处理
            log.debug("<<<<===============处理结束===============>>>>");
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = inSocket.getAddress().getHostAddress();
        String port = String.valueOf(inSocket.getPort());
        log.info("Netty设备连接成功 {}:{} ", ip, port);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = inSocket.getAddress().getHostAddress();
        String port = String.valueOf(inSocket.getPort());
        log.info("Netty设备连接断开 {}:{} ", ip, port);
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = inSocket.getAddress().getHostAddress();
        String port = String.valueOf(inSocket.getPort());
        log.error("远程客户端强迫关闭了一个现有的连接 {}:{} ", cause, ip, port);
        ctx.close();
    }
}
